package service

import (
	"github.com/go-xorm/xorm"
	"xorm.io/builder"

	"im/errcode"
	"im/model"
	"im/requests"
	"im/responses"
	"im/service/orm"
)

type PrivateMessages struct {
	db *xorm.Engine
}

func NewMessagesService() *PrivateMessages {
	return &PrivateMessages{db: orm.GetDB()}
}

func (s *PrivateMessages) GetList(userId uint, fid int64, param requests.GetMessages) (responses.GetPrivateMessages, error) {
	var (
		list = []model.PrivateMessages{}
		err  error
		resp = responses.GetPrivateMessages{}
	)
	query := builder.NewCond().
		Or(builder.NewCond().And(builder.Expr("from=?", userId), builder.Expr("to=?", fid)),
			builder.NewCond().And(builder.Expr("from=?", fid), builder.Expr("to=?", userId)))

	session := s.db.Where(query).Where("created>?", param.BeginTime)
	if !param.EndTime.IsZero() {
		session = session.Where("created<=?", param.EndTime)
	}
	session = session.Where("id>?", param.Cursor).Limit(param.Limit)
	err = session.Desc("created").Find(list)
	if err != nil {
		return resp, errcode.NewError(errcode.DaoFailed, err)
	}
	resp.List = list
	if len(list) > 0 {
		resp.Cursor = int(list[0].Id)
	}
	return resp, nil
}
